//
//  ZWTwiceViewController.m
//  WanEr
//
//  Created by 高文萍 on 16/1/14.
//  Copyright © 2016年 ziwokeji. All rights reserved.
//

#import "ZWTwiceViewController.h"
#import "ZWHeaderView.h"
#import "ZWHeader.h"
#import "ZWAudioHeader.h"
#import "ZWAudioTableViewCell.h"
#import "ZWFirstModel.h"
#import "ZWBaseCollecView.h"
#import "ZWChoseCollectionViewCell.h"
#import "ZWShowCityTableViewCell.h"
#import "ZWPlayerViewController.h"
// 播放
#import "PlayerManager.h"
@interface ZWTwiceViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
// 顶部菜单栏
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *headerImg;
@property (nonatomic, strong) UILabel *headerLabel;
@property (nonatomic, strong) UIButton *returnBut;
@property (nonatomic, strong) UIButton *shareBut;
@property (nonatomic, strong) UIButton *collectBut;//收藏
// 首个tableView
@property (nonatomic, strong) UITableView *audioTableView;
@property (nonatomic, strong) UIView *allHeaderView;
@property (nonatomic, strong) ZWAudioHeader *audioHeaderView;
@property (nonatomic, strong) NSMutableArray *firArr;
@property (nonatomic, strong) ZWFirstModel *modelArr;
@property (nonatomic, strong) NSMutableDictionary *firDic;
@property (nonatomic, strong) ZWAudioTableViewCell *cell;
// 筛选所需
@property (nonatomic, strong) UIView *choseView;
@property (nonatomic, strong) NSMutableArray *choseArr;
@property (nonatomic, assign) BOOL selecChoce;
@property (nonatomic, strong) UIButton *allBut;// 全部景点点击
@property (nonatomic, strong) ZWBaseCollecView *showCollection;
@property (nonatomic, strong) UITableView *showAudioCityTable;
@property (nonatomic, strong) ZWShowCityTableViewCell *showCell;
@property (nonatomic, assign) NSInteger indexNum;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) UIImageView *baseImg;
@property (nonatomic, strong) ZWChoseCollectionViewCell *choseCell;
@property (nonatomic, strong) UILabel *butLabel;
// 播放
@property (nonatomic, strong) PlayerManager *playerManger;
@property (nonatomic, assign) NSInteger indexPlay;
@end

@implementation ZWTwiceViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 导航栏
    [self createHeaderView];
    [self createAllTableView];
    [self createTableData];

    self.audioTableView.hidden = NO;
    
    // 第一个tablecell通知中心将值传到下一页 table
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushPlayerPage:) name:@"tagValue" object:nil];
    // 第二个tablecell通知 collectin
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushVC:) name:@"pushVC" object:nil];
    
    self.playerManger = [PlayerManager playerManager];
    //告诉系统，我们要接受远程控制事件
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
// 响应远程播放控制消息
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl) {
        
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlPlay:
//            [self.playCenter midBtnClicked:nil];
                NSLog(@"暂停播放");
                break;
            case UIEventSubtypeRemoteControlPause:
                //                [self.playCenter midBtnClicked:nil];
                NSLog(@"继续播放");
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"下一曲");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"上一曲");
                break;
            default:
                break;
        }
    }
}
#pragma ---网络请求---
- (void)createTableData
{
    self.firArr = [NSMutableArray array];
    self.firDic = [NSMutableDictionary dictionary];
    [JXRAFNetWorkTool getNetWithURL:[NSString stringWithFormat:@"http://app.ziwoxz.com/agi/scenerie/listing/sid/%@",self.uId] body:self resultKind:JXRJSON headerFile:nil success:^(id result) {
        
        self.firArr = [ZWFirstModel baseModelByArr:result[@"data"][@"sceneries"] arr:self.firArr];
        self.firDic = result[@"data"][@"main_scenerie"];
        [self.audioHeaderView.cityHeaderImg sd_setImageWithURL:[NSURL URLWithString:self.firDic[@"image_url"]] placeholderImage:[UIImage imageNamed:@"景集页面占位图"]];
        
      // 播放数组 传到下一页
        self.modelArr = (ZWFirstModel *)self.firArr[self.indexPlay];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.modelArr.scenic_spots];
        [self.playerManger getPlayListCompletionHandler:arr];
        
        [self.audioTableView reloadData];
        [self.showCollection reloadData];
        [self.showAudioCityTable reloadData];
    } failure:^(NSError *error) {
        
    }];
}

#pragma ----创建导航栏---
- (void)createHeaderView
{
    // 顶部菜单栏
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.view addSubview:self.headerView];
    self.headerImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.headerView addSubview:self.headerImg];
    self.headerImg.image = [UIImage imageNamed:@"iOS顶部菜单栏"];
    self.headerLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    [self.headerView addSubview:self.headerLabel];
    [self.headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerView.mas_centerX);
        make.bottom.equalTo(self.headerView.mas_bottom).offset(-10);
        make.height.equalTo(@(20));
    }];
    self.headerLabel.text = self.cityStr;
    
    self.shareBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareBut setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    [self.shareBut addTarget:self action:@selector(headerClick:) forControlEvents:UIControlEventTouchUpInside];
    self.shareBut.tag = 100;
    [self.headerView addSubview:self.shareBut];
    [self.shareBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-15));
        make.bottom.equalTo(self.headerView.mas_bottom).offset(-10);
        make.width.height.equalTo(@(23));
    }];
    
    self.collectBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectBut.tag = 102;
    [self.collectBut setImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
    [self.collectBut addTarget:self action:@selector(headerClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.collectBut];
    [self.collectBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.headerView.mas_bottom).offset(-10);
        make.right.equalTo(self.shareBut.mas_left).offset(-20);
        make.width.height.equalTo(@(23));
    }];
    
    self.returnBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.returnBut setImage:[UIImage imageNamed:@"Oval 36 + Path 43 + Path 44 + Path 44 Copy-1"] forState:UIControlStateNormal];
    self.returnBut.tag = 101;
    [self.returnBut addTarget:self action:@selector(headerClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.returnBut];
    [self.returnBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(16));
        make.bottom.equalTo(self.headerImg.mas_bottom).offset(-10);
        make.width.equalTo(@(25));
        make.height.equalTo(@(25));
    }];
}
#pragma ---返回按钮 收藏 分享---
- (void)headerClick:(UIButton *)button
{
    switch (button.tag) {
        case 100:{
            NSLog(@"分享");
        }
        break;
        case 101:{
        [self.navigationController popViewControllerAnimated:YES];
        }
        break;
        case 102:{
            NSLog(@"收藏");
        }
        break;
        default:
            break;
    }
    
}
#pragma ----首个tableView---
- (void)createAllTableView
{
    self.allHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 130)];
    self.allHeaderView.backgroundColor = [UIColor colorWithWhite:0.930 alpha:1.000];// 颜色
    self.audioHeaderView = (ZWAudioHeader *)[[[NSBundle mainBundle]loadNibNamed:@"audioHeader" owner:self options:nil]lastObject];// headerXib
    [self.allHeaderView addSubview:self.audioHeaderView];
    self.audioHeaderView.cityHeaderName.text = self.cityStr;// xib
    
    self.audioTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 49) style:UITableViewStylePlain];
    self.audioTableView.showsVerticalScrollIndicator = NO;
    self.audioTableView.showsHorizontalScrollIndicator = NO;
    self.audioHeaderView.frame = CGRectMake(0,0, WIDTH, 130);// 头视图大小
    self.audioTableView.delegate = self;
    self.audioTableView.dataSource = self;
    self.audioTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// 风格 只有一条线 单线
    [self.view addSubview:self.audioTableView];
    self.audioTableView.tableHeaderView = self.allHeaderView;// 头视图
    self.audioTableView.allowsSelection = NO;
    self.audioHeaderView.cityHeaderName.text = self.cityStr;
    self.audioHeaderView.cityHeaderName.font = [UIFont systemFontOfSize:20 weight:2];
    self.audioHeaderView.cityHeaderName.textAlignment = NSTextAlignmentCenter;
    self.audioHeaderView.cityHeaderName.textColor = [UIColor whiteColor];
    // 头部大按钮播放
    [self.audioHeaderView.playerHeaderBut addTarget:self action:@selector(headerBut:) forControlEvents:UIControlEventTouchUpInside];
    
    // 筛选
    [self.audioHeaderView.headerChoseBut addTarget:self action:@selector(ChoseBut:) forControlEvents:UIControlEventTouchUpInside];

    [self.audioHeaderView.changeButImg addTarget:self action:@selector(ChoseBut:) forControlEvents:UIControlEventTouchUpInside];

    [self createChangeView];// 筛选后的界面
    [self createShowCollection];// 街景列表
}
#pragma ---景点showTableView---
- (void)createShowAudioTable
{
    self.showAudioCityTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 49) style:UITableViewStylePlain];
    self.showAudioCityTable.delegate = self;
    self.showAudioCityTable.dataSource = self;
    self.showAudioCityTable.tableHeaderView = self.allHeaderView;
    self.showAudioCityTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.showAudioCityTable];
}
#pragma ---筛选后界面全部景点but---
- (void)createChangeView
{
    self.allBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.allHeaderView addSubview:self.allBut];
    [self.allBut addTarget:self action:@selector(allButClick:) forControlEvents:UIControlEventTouchUpInside];
    self.allBut.backgroundColor = [UIColor whiteColor];
    
    self.butLabel = [[UILabel alloc]init];
    [self.allBut addSubview:self.butLabel];
    self.butLabel.text = @"全部街景";
    self.butLabel.textAlignment = NSTextAlignmentCenter;
    self.butLabel.font = [UIFont systemFontOfSize:14];
    [self.butLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self.allBut).offset(0);
    }];
    
}
#pragma --点击后刷新全部景点---
- (void)allButClick:(UIButton *)button
{
    // 点击全部刷新tableView
  
    self.audioHeaderView.changeLabelAll.text = @"全部";
    if (self.audioTableView) {
        [self creatTable2]; // 创建table2
    }
    [self.showAudioCityTable removeFromSuperview];
    
    [self.audioHeaderView.cityHeaderImg sd_setImageWithURL:[NSURL URLWithString:self.firDic[@"image_url"]] placeholderImage:[UIImage imageNamed:@"景集页面占位图"]];
    [self ChoseBut:UIButtonTypeCustom];
    self.audioTableView.tableHeaderView = self.allHeaderView;
    [self.audioTableView reloadData];
    [self.audioTableView setHidden:NO];
}
- (void)creatTable2
{
    self.audioTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 49) style:UITableViewStylePlain];
    self.audioTableView.showsVerticalScrollIndicator = NO;
    self.audioTableView.showsHorizontalScrollIndicator = NO;
    self.audioHeaderView.frame = CGRectMake(0,0, WIDTH, 130);// 头视图大小
    self.audioTableView.delegate = self;
    self.audioTableView.dataSource = self;
    self.audioTableView.tag = 1000;
    self.audioTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// 风格 只有一条线 单线
    [self.view addSubview:self.audioTableView];
    self.audioTableView.tableHeaderView = self.allHeaderView;// 头视图
    self.audioTableView.allowsSelection = NO;
    self.audioHeaderView.cityHeaderName.text = self.cityStr;
    self.audioHeaderView.cityHeaderName.font = [UIFont systemFontOfSize:20 weight:2];
    self.audioHeaderView.cityHeaderName.textAlignment = NSTextAlignmentCenter;
    self.audioHeaderView.cityHeaderName.textColor = [UIColor whiteColor];
    // 头部大按钮播放
    [self.audioHeaderView.playerHeaderBut addTarget:self action:@selector(headerBut:) forControlEvents:UIControlEventTouchUpInside];
    
    // 筛选
    [self.audioHeaderView.headerChoseBut addTarget:self action:@selector(ChoseBut:) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma ---筛选点击 选择 改变界面样式---
- (void)ChoseBut:(UIButton *)button
{
    self.selecChoce = !self.selecChoce;
    if (self.selecChoce) {
        
        if (self.firArr.count == 0) {
            NSLog(@"空");
        }else{
            // 筛选
            [self.audioHeaderView.headerChoseBut setTitle:@"收起" forState:UIControlStateNormal];
            [self.audioHeaderView.changeButImg setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
            [UIView animateWithDuration:0.3 animations:^{
                
                // header高度
        if (self.firArr.count / 4 == 0) {
            self.allHeaderView.frame = CGRectMake(0, 0, WIDTH, 120 + 55 + 40 + 15);
        }else{
            self.allHeaderView.frame = CGRectMake(0, 0, WIDTH, 120 + 55 + self.firArr.count / 4 * 40 + 15);
                }

        
        self.showAudioCityTable.tableHeaderView = self.allHeaderView;
        self.audioTableView.tableHeaderView = self.allHeaderView;// 头视图

            } completion:^(BOOL finished) {
                // 动画完成后执行
                [self.allBut setHidden:NO];
                [self.allBut mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.audioHeaderView.mas_bottom).offset(10);
                    make.left.equalTo(@(12));
                    make.right.equalTo(@(-12));
                    make.height.equalTo(@(40));
                }];
                
                // 可能会有问题
                if (self.firArr.count / 4 == 0) {
                    self.showCollection.frame = CGRectMake(2, 55 + 130, WIDTH, 38 + 2);
                }else{
                    self.showCollection.frame = CGRectMake(0, 55 + 130, WIDTH, self.firArr.count / 4 * 40);
                }
                [self.showCollection setHidden:NO];
                
                // 刷新collection
//                [self.showCollection reloadData];
                [self.showCollection setHidden:NO];
                
            }];
        }
        
    }else{
        // 收起
        [self.audioHeaderView.headerChoseBut setTitle:@"筛选" forState:UIControlStateNormal];
        [self.audioHeaderView.changeButImg setImage:[UIImage imageNamed:@"Path 114 + Path 115 + 筛选 Copy"] forState:UIControlStateNormal];
            [UIView animateWithDuration:0.3 animations:^{
            [self.showCollection setHidden:YES];
            [self.allBut setHidden:YES];
            self.allHeaderView.frame = CGRectMake(0, 0, WIDTH, 130);
            
        self.showAudioCityTable.tableHeaderView = self.allHeaderView;
        self.audioTableView.tableHeaderView = self.allHeaderView;// 头视图
        
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
}
#pragma ---collection景集列表allHeader上---
- (void)createShowCollection
{
    self.showCollection = [[ZWBaseCollecView alloc]initWithFrame:CGRectZero flowLayoutItemSize:CGSizeMake((WIDTH - 12 * 2 - 3 * 1) / 4, 38) xSpace:1 ySpace:1 sectionInset:UIEdgeInsetsMake(1, 12, 1, 12) cell:[ZWChoseCollectionViewCell class] reuse:@"reuseChose"];
    self.showCollection.backgroundColor = [UIColor clearColor];
    self.showCollection.delegate = self;
    self.showCollection.dataSource = self;
    [self.allHeaderView addSubview:self.showCollection];
}

#pragma ---collection 全部景集 选中景集---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.firArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.choseCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseChose" forIndexPath:indexPath];
    
    self.choseCell.backgroundColor = [UIColor whiteColor];
    self.choseCell.cityChangeLabel.text = ((ZWFirstModel *)self.firArr[indexPath.row]).scenerie_name;
    
    // 点击选中背景图
    UIImageView* selectedBGImg = [[UIImageView alloc] initWithFrame:self.choseCell.bounds];
    selectedBGImg.image = [UIImage imageNamed:@"选中底图"];
    self.choseCell.selectedBackgroundView = selectedBGImg;
    return self.choseCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.indexNum = indexPath.row;
    [self createShowAudioTable];// 选中街景
//    [self.showAudioCityTable reloadData];
    [self.showAudioCityTable setHidden:NO];
    [self.audioTableView removeFromSuperview];
    self.audioHeaderView.changeLabelAll.text = ((ZWFirstModel *)self.firArr[indexPath.row]).scenerie_name;
}
#pragma --allHeader播放全部--
- (void)headerBut:(UIButton *)button
{
    NSLog(@"头部播放");
    ZWPlayerViewController *playerTVC = [ZWPlayerViewController new];
    [self.navigationController pushViewController:playerTVC animated:YES];
}
#pragma ---tableView协议---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.audioTableView) {
        return self.firArr.count;
    }else if(tableView == self.showAudioCityTable){
        return 1;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.audioTableView) {
        static NSString *reuse = @"reuse";
        self.cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!self.cell) {
            self.cell = [[ZWAudioTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        self.modelArr = (ZWFirstModel *)self.firArr[indexPath.row];
        self.indexPlay = indexPath.row;
        [self.cell.firstCellImg sd_setImageWithURL:[NSURL URLWithString:self.modelArr.image_url]placeholderImage:[UIImage imageNamed:@"筛选前占位图"]];
        self.cell.twiceArr = self.modelArr.scenic_spots;
        [self.cell.playerAllBut setImage:[UIImage imageNamed:@"播放2"] forState:UIControlStateNormal];
        [self.cell.playerAllBut addTarget:self action:@selector(clickPlay:) forControlEvents:UIControlEventTouchUpInside];
        self.cell.cityPLabel.text = self.modelArr.scenic_spots[0][@"scenerie_name"];
        // 刷新自定义tablecell
        [self.cell createData];
        return self.cell;

    }else if(tableView == self.showAudioCityTable){
        static NSString *reuse = @"reuseShow";
        self.showCell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!self.showCell) {
            self.showCell = [[ZWShowCityTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        
        self.showCell.showArr = ((ZWFirstModel *)self.firArr[self.indexNum]).scenic_spots;
        self.arr = ((ZWFirstModel *)self.firArr[self.indexNum]).scenic_spots;
        [self.showCell createData];
        
        return self.showCell;
    }
    
    return nil;
}
#pragma --通知push下一页--
- (void)pushPlayerPage:(NSNotification *)notification
{
    ZWPlayerViewController *playeTVC = [ZWPlayerViewController new];
    playeTVC.uId = notification.userInfo[@"id"];
    [self.navigationController pushViewController:playeTVC animated:YES];
}
- (void)pushVC:(NSNotification *)notification
{
    ZWPlayerViewController *playeTVC = [ZWPlayerViewController new];
    playeTVC.uId = notification.userInfo[@"id"];
    [self.navigationController pushViewController:playeTVC animated:YES];
}
- (void)clickPlay:(UIButton *)button
{
    ZWPlayerViewController *playeTVC = [ZWPlayerViewController new];
    [self.navigationController pushViewController:playeTVC animated:YES];
    NSLog(@"播放全部");
    
}
// 返回table cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.audioTableView) {
        if (self.cell.indexP > 3){
            
            return self.modelArr.scenic_spots.count * 47 + 20;
        }else{
            return 3 * 47 + 20;
        }
    }else{
        if (self.arr.count < 4) {
            
            return (WIDTH - 20 * 3) / 3 + (WIDTH - 20 * 5) / 6 + 40 + 20;
        }else{
            return ((WIDTH - 20 * 3) / 3 + (WIDTH - 20 * 5) / 6 + 40) * self.arr.count / 3 + 20;
        }
    }
    

    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
